// 服务列表
// 注意：以接口数据中id为依据进行选择，所以模拟的数据中必须含有不重复的id

interface IGoodsListProps {
  style?: string;
  sourceItems?: Project.IProjectItem[];
  checkedItems?: Project.IProjectItem[];
  onChecked?(e: Project.IProjectItem[]): void;
}
interface IGoodsListData {
  currItems?: Project.IProjectItem[];
}
interface IGoodsLisMethods {
  initData(): void;
  setCheckedData(e): void;
  judgePropsChange(e): boolean;
  handleTap(e): void;
}
Component<IGoodsListData, IGoodsListProps, IGoodsLisMethods>({
  data: {
    currItems: []
  },
  props: {
    sourceItems: [],
    checkedItems: []
  },
  didMount() {
    this.initData();
  },
  didUpdate(prevProps) {
    if (this.judgePropsChange(prevProps)) {
      this.initData();
    }
  },
  methods: {
    initData() {
      const { checkedItems, sourceItems } = this.props;
      const ids = checkedItems.map(item => item.serviceId);
      const currItems: any = [];
      sourceItems.forEach(item => {
        item.checked = ids.includes(item.serviceId);
        currItems.push(item);
      });
      this.setData({
        currItems
      });
    },
    handleTap({
      target: {
        dataset: { index }
      }
    }) {
      const { currItems } = this.data;
      currItems[index].checked = !currItems[index].checked;
      this.setData({
        currItems
      });
      this.setCheckedData(currItems)
    },
    setCheckedData(currItems = []) {
      const newItems = []
      currItems.forEach(item => {
        if (item.checked) {
          newItems.push(item)
        }
      });
      this.props.onChecked && this.props.onChecked(newItems)
    },
    // 判断sourceItems是否改变
    judgePropsChange(prevProps) {
      const prevIds = prevProps.sourceItems.map(item => item.serviceId);
      const ids = this.props.sourceItems.map(item => item.serviceId);
      if (prevIds.length !== ids.length) {
        return true;
      } else if (ids.some(item => !prevIds.includes(item))) {
        return true;
      } else {
        return false;
      }
    }
  }
});
